<template>
    <view class="driver-cert-container">
        <scroll-view scroll-y class="scroll-area">
            <view class="content">
                <!-- 个人信息输入 -->
                <view class="form-section">
                    <view class="section-title">个人信息</view>

                    <!-- 司机姓名 -->
                    <view class="form-item">
                        <text class="form-label">司机姓名:</text>
                        <uv-input v-model="formData.driverName" placeholder="请输入司机姓名" :border="false" :clearable="true"
                            customStyle="background: #f8f9fa; padding: 20rpx; border-radius: 8rpx;" />
                    </view>

                    <!-- 司机身份证号 -->
                    <view class="form-item">
                        <text class="form-label">司机身份证号:</text>
                        <uv-input v-model="formData.driverIdCard" placeholder="请输入司机身份证号" :border="false"
                            :clearable="true" customStyle="background: #f8f9fa; padding: 20rpx; border-radius: 8rpx;" />
                    </view>

                    <!-- 押运人姓名 -->
                    <view class="form-item">
                        <text class="form-label">押运人姓名:</text>
                        <uv-input v-model="formData.escortName" placeholder="请输入押运人姓名" :border="false" :clearable="true"
                            customStyle="background: #f8f9fa; padding: 20rpx; border-radius: 8rpx;" />
                    </view>

                    <!-- 押运人身份证号 -->
                    <view class="form-item">
                        <text class="form-label">押运人身份证号:</text>
                        <uv-input v-model="formData.escortIdCard" placeholder="请输入押运人身份证号" :border="false"
                            :clearable="true" customStyle="background: #f8f9fa; padding: 20rpx; border-radius: 8rpx;" />
                    </view>

                     <!-- 车牌号 -->
                     <view class="form-item">
                        <text class="form-label">车牌号:</text>
                        <uv-input v-model="formData.carnumber" placeholder="请输入车牌号" :border="false"
                            :clearable="true" customStyle="background: #f8f9fa; padding: 20rpx; border-radius: 8rpx;" />
                    </view>

                     <!-- 车辆类型 -->
                     <view class="form-item">
                        <text class="form-label">车辆类型:</text>
                        <uv-input v-model="formData.type" placeholder="请输入车辆类型" :border="false"
                            :clearable="true" customStyle="background: #f8f9fa; padding: 20rpx; border-radius: 8rpx;" />
                    </view>
                </view>

                <!-- 证件上传 -->
                <view class="upload-section">
                    <view class="section-title">证件上传</view>

                    <!-- 押运证 -->
                    <view class="upload-item">
                        <text class="upload-label">押运证 (押运人)</text>
                        <view class="upload-area" @click="chooseImage('escortCert')">
                            <view v-if="!formData.escortCert" class="upload-placeholder">
                                <uv-icon name="plus" size="48" color="#C0C4CC" />
                                <text class="upload-text">上传</text>
                            </view>
                            <image v-else :src="formData.escortCert" mode="aspectFill" class="uploaded-image" />
                        </view>
                    </view>

                    <!-- 车辆行驶证 -->
                    <view class="upload-item">
                        <text class="upload-label">车辆行驶证</text>
                        <view class="upload-area" @click="chooseImage('vehicleReg')">
                            <view v-if="!formData.vehicleReg" class="upload-placeholder">
                                <uv-icon name="plus" size="48" color="#C0C4CC" />
                                <text class="upload-text">上传</text>
                            </view>
                            <image v-else :src="formData.vehicleReg" mode="aspectFill" class="uploaded-image" />
                        </view>
                    </view>

                    <!-- 车辆道路运输许可证 -->
                    <view class="upload-item">
                        <text class="upload-label">车辆道路运输许可证</text>
                        <view class="upload-area" @click="chooseImage('transportPermit')">
                            <view v-if="!formData.transportPermit" class="upload-placeholder">
                                <uv-icon name="plus" size="48" color="#C0C4CC" />
                                <text class="upload-text">上传</text>
                            </view>
                            <image v-else :src="formData.transportPermit" mode="aspectFill" class="uploaded-image" />
                        </view>
                    </view>

                    <!-- 司机驾驶证 -->
                    <view class="upload-item">
                        <text class="upload-label">司机驾驶证</text>
                        <view class="upload-area" @click="chooseImage('driverLicense')">
                            <view v-if="!formData.driverLicense" class="upload-placeholder">
                                <uv-icon name="plus" size="48" color="#C0C4CC" />
                                <text class="upload-text">上传</text>
                            </view>
                            <image v-else :src="formData.driverLicense" mode="aspectFill" class="uploaded-image" />
                        </view>
                    </view>

                    <!-- 司机从业资格证 -->
                    <view class="upload-item">
                        <text class="upload-label">司机从业资格证</text>
                        <view class="upload-area" @click="chooseImage('qualificationCert')">
                            <view v-if="!formData.qualificationCert" class="upload-placeholder">
                                <uv-icon name="plus" size="48" color="#C0C4CC" />
                                <text class="upload-text">上传</text>
                            </view>
                            <image v-else :src="formData.qualificationCert" mode="aspectFill" class="uploaded-image" />
                        </view>
                    </view>
                </view>
            </view>
        </scroll-view>

        <!-- 提交按钮 -->
        <view class="submit-section">
            <uv-button text="提交" type="primary" size="large" :custom-style="submitButtonStyle"
                @click="submitCertification" />
        </view>
    </view>
</template>

<script setup lang="ts">
import { ref } from 'vue'
import { UserInfoManager } from '@/utils/userInfo'
import { useRequest } from '@/api'

const { API_DRIVER_CERT_SUBMIT } = useRequest()

// 表单数据
const formData = ref<any>({
    driverName: '',
    driverIdCard: '',
    escortName: '',
    escortIdCard: '',
    carnumber:'',
    type:'',
    escortCert: '',
    vehicleReg: '',
    transportPermit: '',
    driverLicense: '',
    qualificationCert: ''
})

// 当前上传的证件类型
const currentUploadType = ref('')

// 提交按钮样式
const submitButtonStyle = {
    backgroundColor: '#FF6B35',
    borderColor: '#FF6B35',
    borderRadius: '24rpx',
    height: '88rpx',
    fontSize: '32rpx',
    fontWeight: '600',
    width: '100%'
}

// 选择图片
const chooseImage = (type: string) => {
    currentUploadType.value = type
    uni.chooseImage({
        count: 1,
        sizeType: ['compressed'],
        sourceType: ['album', 'camera'],
        success: (res) => {
            console.log('选择图片成功:', res.tempFilePaths[0])
            uploadImage(res.tempFilePaths[0], type)
        },
        fail: (err) => {
            console.log('选择图片失败:', err)
            uni.showToast({ title: '选择图片失败', icon: 'none' })
        }
    })
}

// 上传图片
const uploadImage = async (filePath: string, type: string) => {
    uni.showLoading({ title: '上传中...' })

    try {
        const uploadRes = await uni.uploadFile({
            url: import.meta.env.VITE_APP_API_BASEURL + '/api/index/upload',
            filePath: filePath,
            name: 'file',
            formData: {
                type: type // 文件类型标识
            },
           
            success: (res) => {
                try {
                    const data = JSON.parse(res.data)
                    console.log('图片上传响应:', data)
                    if (data.code === 1) {
                        // 上传成功，更新对应的证件图片
                        formData.value[type] = data.data.fullurl
                        uni.showToast({ title: '上传成功', icon: 'success' })
                    } else {
                        uni.showToast({ title: data.msg || '上传失败', icon: 'none' })
                    }
                } catch (e) {
                    console.error('解析上传响应失败:', e)
                    uni.showToast({ title: '上传失败', icon: 'none' })
                }
            },
            fail: (err) => {
                console.error('图片上传失败:', err)
                uni.showToast({ title: '上传失败', icon: 'none' })
            }
        })
    } catch (error) {
        console.error('图片上传异常:', error)
        uni.showToast({ title: '上传异常', icon: 'none' })
    } finally {
        uni.hideLoading()
    }
}

// 提交认证
const submitCertification = async () => {
    // 验证必填字段
    if (!formData.value.driverName.trim()) {
        uni.showToast({ title: '请输入司机姓名', icon: 'none' })
        return
    }
    if (!formData.value.driverIdCard.trim()) {
        uni.showToast({ title: '请输入司机身份证号', icon: 'none' })
        return
    }
    if (!formData.value.escortName.trim()) {
        uni.showToast({ title: '请输入押运人姓名', icon: 'none' })
        return
    }
    if (!formData.value.escortIdCard.trim()) {
        uni.showToast({ title: '请输入押运人身份证号', icon: 'none' })
        return
    }
    if (!formData.value.carnumber.trim()) {
        uni.showToast({ title: '请输入车牌号', icon: 'none' })
        return
    }
    if (!formData.value.type.trim()) {
        uni.showToast({ title: '请输入车辆类型', icon: 'none' })
        return
    }
    // 验证证件上传
    if (!formData.value.escortCert) {
        uni.showToast({ title: '请上传押运证', icon: 'none' })
        return
    }
    if (!formData.value.vehicleReg) {
        uni.showToast({ title: '请上传车辆行驶证', icon: 'none' })
        return
    }
    if (!formData.value.transportPermit) {
        uni.showToast({ title: '请上传车辆道路运输许可证', icon: 'none' })
        return
    }
    if (!formData.value.driverLicense) {
        uni.showToast({ title: '请上传司机驾驶证', icon: 'none' })
        return
    }
    if (!formData.value.qualificationCert) {
        uni.showToast({ title: '请上传司机从业资格证', icon: 'none' })
        return
    }

    // 验证身份证号格式
    if (!/^\d{17}[\dXx]$/.test(formData.value.driverIdCard)) {
        uni.showToast({ title: '请输入正确的司机身份证号', icon: 'none' })
        return
    }
    if (!/^\d{17}[\dXx]$/.test(formData.value.escortIdCard)) {
        uni.showToast({ title: '请输入正确的押运人身份证号', icon: 'none' })
        return
    }

    uni.showLoading({ title: '提交中...' })

    try {
        const params = {
            isdriver: UserInfoManager.lastrole(),
            username: formData.value.driverName,
            idcard: formData.value.driverIdCard,
            escortusername: formData.value.escortName,
            escortidcard: formData.value.escortIdCard,
            carnumber: formData.value.carnumber,
            type: formData.value.type,
            escortcertificate: formData.value.escortCert,
            vehiclelicense: formData.value.vehicleReg,
            vehiclequalification: formData.value.transportPermit,
            drivinglicense: formData.value.driverLicense,
            driverqualification: formData.value.qualificationCert
        }

        const res = await API_DRIVER_CERT_SUBMIT(params)
        if (res.code === 1) {
            uni.showToast({ title: '认证提交成功', icon: 'success' })
            // 延迟返回上一页
            setTimeout(() => {
                uni.navigateBack()
            }, 500)
        } 
    } catch (error) {
        
    } finally {
        uni.hideLoading()
    }
}
</script>

<style lang="scss" scoped>
.driver-cert-container {
    min-height: 100vh;
    background: #f6f7f9;
    display: flex;
    flex-direction: column;
}

.scroll-area {
    flex: 1;
    padding: 20rpx 0;
}

.content {
    padding: 0 24rpx;
}

.form-section,
.upload-section {
    background: #fff;
    border-radius: 16rpx;
    padding: 24rpx;
    margin-bottom: 20rpx;
    box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.06);
}

.section-title {
    font-size: 32rpx;
    font-weight: 600;
    color: #333;
    margin-bottom: 24rpx;
}

.form-item {
    margin-bottom: 24rpx;

    &:last-child {
        margin-bottom: 0;
    }
}

.form-label {
    display: block;
    font-size: 28rpx;
    color: #333;
    margin-bottom: 12rpx;
    font-weight: 500;
}

.upload-item {
    margin-bottom: 32rpx;

    &:last-child {
        margin-bottom: 0;
    }
}

.upload-label {
    display: block;
    font-size: 28rpx;
    color: #333;
    margin-bottom: 16rpx;
    font-weight: 500;
}

.upload-area {
    width: 100%;
    height: 300rpx;
    border: 2rpx dashed #C0C4CC;
    border-radius: 12rpx;
    background: #f8f9fa;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    position: relative;
    overflow: hidden;
}

.upload-placeholder {
    display: flex;
    flex-direction: column;
    align-items: center;
    gap: 16rpx;
}

.upload-text {
    font-size: 28rpx;
    color: #C0C4CC;
}

.uploaded-image {
    width: 100%;
    height: 100%;
    object-fit: cover;
}

.submit-section {
    padding: 24rpx;
    background: #fff;
    border-top: 1rpx solid #f0f0f0;
}
</style>